import { ref } from "vue";

export const socket = ref();
export const initWebsocket=()=>{
	if(!uni.getStorageSync('token')){
		console.log("ho")
		uni.setStorageSync('login',true)
	}
	const token = uni.getStorageSync('token')
	socket.value = uni.connectSocket({
		url: 'ws://localhost:8080/websocket',
		header: {
			'content-type': 'application/json'
		},
		protocols: [token.result],
		method: 'GET',
		complete(result) {
			console.log("好的",result)
		}
	});
	socket.value.onOpen((res)=>{
		console.log("连接打开")
		socket.value.send({data:"heart"}); 
	})
	socket.value.onClose((res)=>{
		console.log("连接关闭")
		socket.value = uni.connectSocket({
			url: 'ws://localhost:8080/websocket',
			header: {
				'content-type': 'application/json'
			},
			protocols: [token.result],
			method: 'GET',
			complete(result) {
				console.log("好的",result)
			}
		});
	})
	socket.value.onError((res)=>{
		console.log("连接错误",res)
	})
	socket.value.onMessage((event)=>{
		console.log("消息接受",event)
		if(event.data=='ok'){
			setTimeout(function(){
				socket.value.send({data:"heart"}); 
			},10000)
		}else{
			const msgBody = JSON.parse(event.data)
			// uni.setStorageSync('socketmsg',msgBody)
		}
	})
	return socket;
}

export const closeSocket=()=>{
	socket.value.close()
}
